<template>
  <div style="height:900px;">
    <div class="login-container">
      <div class="form-container sign-in-container">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="80px;">
          <div class="headstyle">
            <img id="logo" :src="logoMini">
            <span style="font-family: '隶书'; font-size: 35px;">中山大学</span>
            <span style="margin: 0 5px;"> | </span>
            <span style="font-family: '方正舒体'; font-size: 35px;">数字百团</span>
          </div>
          <div>
            <el-form-item prop="email" style="margin-top: 30px;margin-left: 100px;">
              <el-input class="input_text" type="email" v-model="loginForm.email" placeholder="请输入邮箱" style="width: 500px;">
                <template #prefix>
                  <el-icon class="el-input__icon"><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>
          <div>
            <el-form-item prop="password" style="margin-top: 30px;margin-left: 100px;">
              <el-input class="input_text" :type="isShowPassword1 ? 'text' : 'password'" v-model="loginForm.password" style="width: 500px;" @keyup.enter="handleLogin" placeholder="请输入密码">
                <template #prefix>
                  <el-icon class="el-input__icon"><Unlock /></el-icon>
                </template>
                <template #suffix>
                  <i class="iconfont el-input__icon login-content-password" @click="isShowPassword1 = !isShowPassword1">
                    <img :src="biyan" alt="biyan" v-if="isShowPassword1">
                    <el-icon v-if="!isShowPassword1"><View /></el-icon>
                  </i>
                </template>
              </el-input>
            </el-form-item>
          </div>
          <div style="text-align:right; margin-top: 20px;">
            <el-link type="primary" @click="showRegisterPanel = true">还未注册？去注册</el-link>
          </div>
          <button type="button" @click="handleLogin" style=" margin-left:100px;margin-top: 20px;width: 300px;height: 30px;display: flex; justify-content: center; align-items: center; font-size: 15px;">登录</button>
        </el-form>
      </div>
    </div>
    <el-dialog title="注册" v-model="showRegisterPanel">
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" label-width="120px">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="registerForm.studentId" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="registerForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input :type="isShowPassword2 ? 'text' : 'password'" v-model="registerForm.password" placeholder="请输入密码">
            <template #prefix>
              <el-icon class="el-input__icon"><Unlock /></el-icon>
            </template>
            <template #suffix>
              <i class="iconfont el-input__icon login-content-password" @click="isShowPassword2 = !isShowPassword2">
                <img :src="biyan" alt="biyan" v-if="isShowPassword2">
                <el-icon v-if="!isShowPassword2"><View /></el-icon>
              </i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input :type="isShowPassword3 ? 'text' : 'password'" v-model="registerForm.confirmPassword" placeholder="请输入密码">
            <template #prefix>
              <el-icon class="el-input__icon"><Unlock /></el-icon>
            </template>
            <template #suffix>
              <i class="iconfont el-input__icon login-content-password" @click="isShowPassword3 = !isShowPassword3">
                <img :src="biyan" alt="biyan" v-if="isShowPassword3">
                <el-icon v-if="!isShowPassword3"><View /></el-icon>
              </i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="registerForm.phone" />
        </el-form-item>
        <el-form-item label="所在校区" prop="campus">
          <el-select v-model="registerForm.campus" placeholder="请选择">
            <el-option label="广州校区南校园" value="广州校区南校园"></el-option>
            <el-option label="广州校区东校园" value="广州校区东校园"></el-option>
            <el-option label="广州校区北校园" value="广州校区北校园"></el-option>
            <el-option label="深圳校区" value="深圳校区"></el-option>
            <el-option label="珠海校区" value="珠海校区"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-select v-model="registerForm.major" placeholder="请选择">
            <el-option label="软件工程" value="软件工程"></el-option>
            <el-option label="计算机科学与技术" value="计算机科学与技术"></el-option>
            <el-option label="心理学" value="心理学"></el-option>
            <el-option label="土木工程" value="土木工程"></el-option>
            <el-option label="微电子科学与技术" value="微电子科学与技术"></el-option>
            <el-option label="历史学" value="历史学"></el-option>
            <el-option label="哲学" value="哲学"></el-option>
            <el-option label="旅游学" value="旅游学"></el-option>
            <el-option label="工商管理" value="工商管理"></el-option>
            <el-option label="数学" value="数学"></el-option>
            <el-option label="物理学" value="物理学"></el-option>
            <el-option label="国际金融" value="国际金融"></el-option>
            <el-option label="音乐学院" value="音乐学院"></el-option>
            <el-option label="法学" value="法学"></el-option>
            <el-option label="新闻传播" value="新闻传播"></el-option>
            <el-option label="医学院" value="医学院"></el-option>
            <el-option label="电子信息工程" value="电子信息工程"></el-option>
            <el-option label="自动化" value="自动化"></el-option>
            <el-option label="汉语言" value="汉语言"></el-option>
            <el-option label="生物医学工程" value="生物医学工程"></el-option>
            <el-option label="化学工程" value="化学工程"></el-option>
            <el-option label="材料学" value="材料学"></el-option>
            <el-option label="农学" value="农学"></el-option>
            <el-option label="临床医学" value="临床医学"></el-option>
            <el-option label="英语专业" value="英语专业"></el-option>
            <el-option label="中法核工程与技术" value="中法核工程与技术"></el-option>
            <el-option label="人工智能" value="人工智能"></el-option>
            <el-option label="测绘工程与技术" value="测绘工程与技术"></el-option>
            <el-option label="海洋科学与技术" value="海洋科学与技术"></el-option>
            <el-option label="地球工程与技术" value="地球工程与技术"></el-option>
            <el-option label="市场营销" value="市场营销"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="registerForm.grade" placeholder="请选择">
            <el-option label="大一" value="大一"></el-option>
            <el-option label="大二" value="大二"></el-option>
            <el-option label="大三" value="大三"></el-option>
            <el-option label="大四" value="大四"></el-option>
            <el-option label="研一" value="研一"></el-option>
            <el-option label="研二" value="研二"></el-option>
            <el-option label="研三" value="研三"></el-option>
            <el-option label="博士" value="博士"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="政治面貌" prop="politicalStatus">
          <el-select v-model="registerForm.politicalStatus" placeholder="请选择">
            <el-option label="群众" value="群众"></el-option>
            <el-option label="共青团员" value="共青团员"></el-option>
            <el-option label="党员" value="党员"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="中大邮箱" prop="sysuEmail">
          <el-input v-model="registerForm.sysuEmail" />
        </el-form-item>
        <el-form-item label="备用邮箱" prop="alternateEmail">
          <el-input v-model="registerForm.alternateEmail" />
        </el-form-item>
        <el-form-item label="个人简介" prop="bio">
          <el-input type="textarea" v-model="registerForm.bio" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister">注册</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import logoMini from "@/assets/logo-mini.svg"
import biyan from "@/assets/iconfont-biyan.svg"
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      username: '',
      password: '',
      captcha: '',
      logoMini,
      biyan,
      captchaImage: '',
      uid: '202',
      isPanelActive: false,
      isShowPassword1: false,
      isShowPassword2: false,
      isShowPassword3: false,
      captchaSrc: '',
      loginForm: {
        email: '',
        password: '',
        verifyCode: '',
        verifyKey: ''
      },
      loginRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
          { validator: this.validateEmailDomain, trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
      },
      showRegisterPanel: false,
      registerForm: {
        studentId: '',
        name: '',
        password: '',
        confirmPassword: '',
        phone: '',
        campus: '',
        major: '',
        grade: '',
        politicalStatus: '',
        sysuEmail: '',
        alternateEmail: '',
        bio: ''
      },
      registerRules: {
        studentId: [
          { required: true, message: '请输入学号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (value !== this.registerForm.password) {
              callback(new Error('两次输入的密码不一致'));
            } else {
              callback();
            }
          }, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        campus: [
          { required: true, message: '请选择所在校区', trigger: 'change' }
        ],
        major: [
          { required: true, message: '请输入专业', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        politicalStatus: [
          { required: true, message: '请选择政治面貌', trigger: 'change' }
        ],
        sysuEmail: [
          { required: true, message: '请输入中大邮箱', trigger: 'blur' },
          { validator: this.validateEmailDomain, trigger: ['blur', 'change'] }
        ],
        alternateEmail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        bio: []
      },
    };
  },
  methods: {
    validateEmailDomain(rule, value, callback) {
      const validDomains = ['@mail2.sysu.edu.cn', '@mail.sysu.edu.cn'];
      if (!value) {
        callback();
      } else {
        const isValid = validDomains.some(domain => value.endsWith(domain));
        if (!isValid) {
          callback(new Error('请使用中大邮箱登录'));
        } else {
          callback();
        }
      }
    },
    async handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            const formData = new FormData();
            formData.append('email', this.loginForm.email);
            formData.append('password', this.loginForm.password);
            const response = await axios.post('/login', formData);
            this.$store.dispatch('saveUserInfo', response.data.data.user);
            ElMessage.success("登录成功！");

            await new Promise(resolve => setTimeout(resolve, 1000));
            this.$router.push('/home');
          } catch (error) {
            console.log(error);
            ElMessage.error("邮箱或密码不正确！");
          }
        } else {
          ElMessage.error("请输入正确的邮箱！");
        }
      });
    },
    async handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          try {
            const reformData = new FormData();
            reformData.append('UID', this.registerForm.studentId);
            reformData.append('Uname', this.registerForm.name);
            reformData.append('Password', this.registerForm.password);
            reformData.append('Phone', this.registerForm.phone);
            reformData.append('Campus', this.registerForm.campus);
            reformData.append('Major', this.registerForm.major);
            reformData.append('PoliticsStatus', this.registerForm.politicalStatus);
            reformData.append('Grade', this.registerForm.grade);
            reformData.append('Email', this.registerForm.sysuEmail);
            reformData.append('BackupEmail', this.registerForm.alternateEmail);
            reformData.append('Intro', this.registerForm.bio);
            console.log(reformData);
            const response = await axios.post('/register', reformData);
            ElMessage.success("注册成功！");
            this.showRegisterPanel = false;
          } catch (error) {
            console.log(error);
            ElMessage.error("注册失败，该用户已注册！");
          }
        } else {
          ElMessage.error("请填写正确的信息！");
        }
      });
    },
    async getCaptcha() {
      this.captchaImage = 'http://example.com/captcha?timestamp=' + Date.now();
    }
  },
  mounted() {
    this.getCaptcha();
  }
}
</script>

<style scoped>
.login-container {
  padding: 20px;
  border: 1px solid #144920;
  background: #fbfbfb;
  border-radius: 10px;
  box-shadow: 0 14px 28px rgba(10, 66, 23, 0.22), 0 10px 10px rgba(10, 66, 23, 0.22);
  position: absolute;
  margin-top: 120px;
  margin-left: 420px;
  width: 500px;
}
.headstyle {
  margin-top: 20px;
  margin-left: 70px;
  white-space: nowrap;
}
.login-content-password {
  display: inline-block;
  width: 20px;
  cursor: pointer;
}
.login-content-password :hover {
  color: #909399;
}
.form-container {
  height: 100%;
  transition: all .6s ease-in-out;
}
.form-container button {
  background-image: linear-gradient(120deg,#429dda,#a1c4fd,#cc9ce0);
  border: none;
  background-size: 200%;
  color: #fff;
  transition: .5s;
}
.form-container button:hover {
  background-position: right;
}
.sign-in-container {
  left: 200;
  width: 80%;
}
label {
  display: block;
  margin-bottom: 5px;
}
input[type="text"],
input[type="password"] {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
}
button {
  display: block;
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}
button:hover {
  background-color: #0056b3;
}
img {
  cursor: pointer;
}
</style>
